package com.massyframework.beanskin.maven.plugin;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

import com.massyframework.beanskin.maven.plugin.util.IOUtils;

/**
 * keyStore信息
 * @author huangkh
 *
 */
public class KeyStoreInformation {
	
	private String keyStore;
	private String keyStorePass;
	private String alias;
	private String keyPass;
	
	/**
	 * 构造方法
	 * @param builder {@link Builder}
	 */
	protected KeyStoreInformation(Builder builder) {
		this.keyStore = Objects.requireNonNull(builder.keyStore, "\"keyStore\" cannot be null.");
		this.keyStorePass = Objects.requireNonNull(builder.keyStorePass, "\"keyStorePass\" cannot be null.");
		this.alias = Objects.requireNonNull(builder.alias, "\"alias\" cannot be null.");
		this.keyPass = Objects.requireNonNull(builder.keyPass, "\"keyPass\" cannot be null.");
	}


	/**
	 * @return the keyStoreFile
	 */
	public String getKeyStore() {
		return keyStore;
	}

	/**
	 * @return the keyStorePass
	 */
	public String getKeyStorePass() {
		return keyStorePass;
	}

	/**
	 * @return the alias
	 */
	public String getAlias() {
		return alias;
	}

	/**
	 * @return the keyPass
	 */
	public String getKeyPass() {
		return keyPass;
	}
	
	public static Builder newBuilder() {
		return new Builder();
	}
	
	public static Builder newBuilder(File config) throws IOException{
		Builder result = new Builder();
		
		if (config != null) {
			InputStream is = null;
			try {
				is = new FileInputStream(config);
				Properties prop = new Properties();
				prop.load(is);
				
				result.keyStore(prop.getProperty("keyStore"))
					.keyStorePass(prop.getProperty("keyStorePass"))
					.alias(prop.getProperty("alias"))
					.keyPass(prop.getProperty("keyPass"));
			}finally {
				IOUtils.close(is);
			}
		}
		
		return result;
	}
	
	/**
	 * 构建器
	 * @author huangkh
	 *
	 */
	public static class Builder {
		private String keyStore;
		private String keyStorePass;
		private String alias;
		private String keyPass;
		
		public Builder keyStore(String value) {
			this.keyStore = value;
			return this;
		}
		
		public Builder keyStorePass(String value) {
			this.keyStorePass = value;
			return this;
		}
		
		public Builder alias(String value) {
			this.alias = value;
			return this;
		}
		
		public Builder keyPass(String value) {
			this.keyPass = value;
			return this;
		}
		
		public KeyStoreInformation build() {
			return new KeyStoreInformation(this);
		}
	}
}
